import * as fs from 'fs';
import * as path from 'path';
import { pathToFileURL } from 'url';
import { _paths } from './paths';

declare const global: any;

// 读取宿主 package.json 的 name 字段
function getHostName(): string {
  try {
    const pkgPath = path.join(_paths.root, 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
    return pkg.name || '';
  } catch (e) {
    return '';
  }
}

// 判断宿主类型
type HostType = 'yunzaijs' | 'trss' | 'miao' | 'other';
function getHostType(): HostType {
  const name = getHostName();
  if (name === 'trss-yunzai') return 'trss';
  if (name === 'miao-yunzai') return 'miao';
  if (name === 'yunzai-pe' || name === 'yunzai-core') return 'yunzaijs';
  return 'other';
}

// 动态导入依赖
let Plugin: any, Segment: any, Redis: any;
const hostType = getHostType();

if (hostType === 'trss' || hostType === 'miao' || hostType === 'other') {
  // trss/miao/other
  // plugin基类路径兼容trss/miao等
  const pluginPath = pathToFileURL(path.join(_paths.root, 'lib', 'plugins', 'plugin.js')).href;
  const pluginModule = await import(pluginPath);
  Plugin = pluginModule.default || pluginModule;
  Segment = global.segment || (global.segment = global.oicq ? global.oicq.segment : global.icqq ? global.icqq.segment : undefined);
  Redis = global.redis;
} else if (hostType === 'yunzaijs') {
  // yunzai-pe/yunzai-core
  await import('yunzaijs').then(yunzaijs => {
    Plugin = yunzaijs.Plugin;
    Segment = yunzaijs.Segment;
    Redis = yunzaijs.Redis;
  });
}

// logger全局
const logger = global.logger;

export { hostType, logger, Plugin, Redis, Segment };
